package vn.sunnet.backviet01.game.coloa.util;

import org.anddev.andengine.engine.camera.Camera;

import vn.sunnet.backviet01.game.coloa.constant.Constants;

public class MyCamera extends Camera {
	private static final long TIME_SHAKE = 1000;

	private static final long TIME_DISTANCE = 80;
	private int count = -1;

	private long startShake = 0;

	private int safeFactor = 1;

	private float pInitialPosistionX;
	private float pInitialPosistionY;

	private boolean isShake;

	public MyCamera(float pX, float pY, float pWidth, float pHeight) {
		super(pX, pY, pWidth, pHeight);
		isShake = false;
		pInitialPosistionX = pX;
		pInitialPosistionY = pY;
	}

	public boolean isShake() {
		return isShake;
	}

	public void setShake(boolean isShake) {
		this.isShake = isShake;
		startShake = System.currentTimeMillis();
		count = 0;
	}

	public void onUpdate(final float pSecondsElapsed) {
		if (isShake) {
			final long current = System.currentTimeMillis();
			
			if (current < startShake + TIME_SHAKE) {
				if (current > startShake + TIME_DISTANCE * count) {
					safeFactor = safeFactor * (-1);
					this.offsetCenter(2 * safeFactor, 2 * safeFactor);
					count++;
				}
			} else {
				this.setCenter(pInitialPosistionX + Constants.CAMERA_WIDTH / 2,
						pInitialPosistionY + Constants.CAMERA_HEIGHT / 2);
				isShake = false;
				startShake = 0;
				count = 0;
			}

		}
		super.onUpdate(pSecondsElapsed);
	}
}
